package cn.tedu.csmall.passport.filter;

import cn.tedu.csmall.passport.security.LoginPrincipal;
import cn.tedu.csmall.passport.web.JsonResult;
import cn.tedu.csmall.passport.web.ServiceCode;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * JWT过滤器,负责过滤所有请求都需要的部分代码
 */
@Slf4j
@Component
public class JwtAuthorizationFilter extends OncePerRequestFilter {
    public JwtAuthorizationFilter() {
        log.debug("创建过滤器对象:JwtAuthorizationFilter");
    }
    @Value("${csmall.jwt.secret-key}")
    private String secretKey;
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        log.debug("JwtAuthorizationFilter开始执行过滤...");
        String jwt = request.getHeader("Authorization");
        log.debug("获取客户端的JWT,{}",jwt);
        if (!StringUtils.hasText(jwt)){
            log.debug("获取到的JWT被视为无效,当前过滤器放行....");
            filterChain.doFilter(request,response);
            return;
        }
        log.debug("获取到的JWT被视为有效,准备解析JWT...");
        response.setContentType("application/json;charset=utf-8");
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secretKey)
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (ExpiredJwtException e) {
            log.debug("解析JWT时出现ExpiredJwtException");
            String message="非登录信息已过期,请重新登录1!";
            JsonResult<Void> jsonResult = JsonResult.fail(ServiceCode.ERR_JWT_EXPIRED,message);
            String s = JSON.toJSONString(jsonResult);
            PrintWriter writer = response.getWriter();// 字符输出流
            writer.println(s);
            return;
        } catch (MalformedJwtException e) {
            log.debug("解析JWT时出现MalformedJwtException,JWT数据有误!");
            String message="非法访问!";
            JsonResult<Void> jsonResult = JsonResult.fail(ServiceCode.ERR_JWT_MALFORMED,message);
            String s = JSON.toJSONString(jsonResult);
            PrintWriter writer = response.getWriter();// 字符输出流
            writer.println(s);
            return;
        } catch (SignatureException e) {
            log.debug("解析JWT时出现签名异常");
            String message="非法访问!";
            JsonResult<Void> jsonResult = JsonResult.fail(ServiceCode.ERR_JWT_SIGNATRUE,message);
            String s = JSON.toJSONString(jsonResult);
            PrintWriter writer = response.getWriter();// 字符输出流
            writer.println(s);
            return;
        } catch (Throwable e) {
            log.debug("解析JWT时出现Throwable异常,需要开发人员在JWT过滤器中自行处理异常");
            String message = "你有异常没有处理，请根据服务器端控制台的信息，补充对此类异常的处理！！！";
            PrintWriter writer = response.getWriter();// 字符输出流
            writer.println(message);
            return;
        }

        // 获取JWT中的管理员信息
        String username = claims.get("username", String.class);
        Long id = claims.get("id", Long.class);
        log.debug("从JWT中获取id:{}",id);
        String authorities1 = claims.get("s", String.class);
        log.debug("从JWT中获取的authorities:{}",authorities1);
        List<GrantedAuthority> authorities2 = JSON.parseArray(authorities1, GrantedAuthority.class);
       // List<GrantedAuthority> authorities = new ArrayList();
       // GrantedAuthority authority = new SimpleGrantedAuthority("这是一个假权限");
        //authorities.add(authority);
        LoginPrincipal loginPrincipal = new LoginPrincipal(id,username);
        //过滤器继续向后执行,即:放行
        Authentication authentication = new UsernamePasswordAuthenticationToken(loginPrincipal,null,authorities2);
        // 将Authentication对象存入到SecurityContext
        log.debug("向SecurityContext中存入认证信息：{}", authentication);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // 过滤器链继续向后传递，即：放行
        log.debug("JWT过滤器执行完毕，放行！");
        filterChain.doFilter(request,response);
    }

}
